<?php
namespace app\spadmin\controller\auth;
use app\common\controller\Backend;

class Group extends Backend{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AuthGroup');
        $this->assign('auth_group',$this->auth->getGroupContentX());
        
    }
    public function index(){
        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            $data = $this->request->param();
            if (isset($data['keywords']) && $data['keywords']) {
                $map['name'] = ['like', '%' . $data['keywords'] . '%'];
            }
            if (isset($data['status']) && $data['status']) {
                $map['status'] = $data['status'];
            } else {
                $map['status'] = 1;
            }
            $list =   $this->model->where($map)->paginate($data['limit'])->toArray();
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['parent_name'] = $value['pid']=='0'?'无上级':$this->model->where('id',$value['pid'])->value('name');
            }
            return $this->result($list);
        }
        return $this->view->fetch();
    }
    public function add(){
        $menu = $this->auth->getAllMenu();
        foreach ($menu as $key => $value) {
            $nav[] = [
                'id'        => strval($value['id']),
                'title'     => $value['title'],
                'checkArr'  => '0',
                'parentId'  => strval($value['pid'])
            ];
        }

        $this->assign('node', json_encode($nav, 1));
        return $this->view->fetch('edit');
    }

    public function edit($id=null){
        $row = $this->model->get(['id'=>$id]);
        if($this->request->isPost()){
            if($row == null){
                $row = $this->model;
            }
            $data = $this->request->post('',[],'strip_tags');
            $result = $row->validate()->allowField(true)->save($data,$data['id']?['id'=>$data['id']]:null);
            if($result === false){
                $this->error($row->getError());
            }
            $this->success('操作成功');
        }
        $rules = (isset($row['rules']) && $row['rules'])?explode(',',$row['rules']): [];
        $menu = $this->auth->getAllMenu();
        if ($menu) {
            foreach ($menu as $key => $value) {
                $nav[] = [
                    'id'        => strval($value['id']),
                    'title'     => $value['title'],
                    'checkArr'  => in_array($value['id'],$rules ) ? '1' : '0',
                    'parentId'  => strval($value['pid'])
                ];
            }
        }
        $this->assign('node', json_encode($nav, 1));
        $this->assign('info',$row);
        return $this->view->fetch();
    }
    
}